/**
 * Baijiahulian.com Inc. Copyright (c) 2014-2016 All Rights Reserved.
 */
package com.baijia.authentication.principal.populator;

import com.baijia.authentication.Authentication;
import com.baijia.authentication.AuthenticationMetaDataPopulator;
import com.baijia.authentication.principal.Credentials;
import com.baijia.authentication.principal.credentials.UserCredentials;
import com.baijia.dao.UserDao;
import com.baijia.dao.po.User;
import com.baijia.util.JacksonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @title UserMetaDataPopulator
 * @desc TODO
 * @author macrohuang
 * @date Jan 20, 2016
 * @version 1.0
 */
@Component
public class UserMetaDataPopulator implements AuthenticationMetaDataPopulator {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String USER = "user";

    @Autowired
    private UserDao userDao;

    @Override
    public Authentication populateAttributes(Authentication authentication, Credentials credentials) {
        UserCredentials userCredentials = (UserCredentials) credentials;
        String mobile = userCredentials.getUsername();

        logger.debug("Try to populate user username : {}", mobile);
        User user = userDao.getUserByMobile(mobile);
        authentication.getAttributes().put(ACCOUNT_ID, user.getId());
        authentication.getAttributes().put(ACCOUNT_NUMBER, user.getNumber());
        authentication.getAttributes().put(ACCOUNT_MOBILE, user.getMobile());
        try {
            user.setPassword(null);
            authentication.getAttributes().put(USER, JacksonUtil.obj2Str(user));
        } catch (IOException e) {
            logger.error("save user into dession error!", e);
        }
        return authentication;
    }

    @Override
    public boolean supports(Credentials credentials) {
        return credentials instanceof UserCredentials;
    }
}
